import { defineStore } from 'pinia'
import { Response } from '../utils/interfaces';
import { ref } from 'vue'
import api from '@/api'

export const userStore = defineStore('user', () => {
	const userInfo = ref(null);
	const userId = ref(null);
	const dept = ref(null);
	
	const setInfo = (u:any) => {
		userInfo.value = u
	}
	
	const setDept = (i:any) => {
		dept.value = i
	}
	
	const setUserId = (id:any) => {
		userId.value = id
	}
	const reset = () => {
		userInfo.value = null
		userId.value = null
		dept.value = null
	}
	const getInfo = () => {
		return new Promise((resolve, reject) => {
			api.user.getInfo().then(res => {
				const user = res.user
				setUserId(user.userId)
				setInfo(user)
				setDept(user.dept)
				// #ifdef APP-PLUS
				// if (isVersion) {
				// 	plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
				// 		uni.setStorageSync("curversion", widgetInfo.version)
				// 		let curversion = widgetInfo.version;
				// 		hotupdate.getAppByVersion(curversion, true)
				// 	})
				// 	plus.navigator.closeSplashscreen()
				// }
				// #endif
				uni.setStorage({
					key: 'userId',
					data: user.userId,
					success: function() {
						resolve(user)
					}
				})
			}).catch(error => {
				reject(error)
			})
		})
	}
	
	const login = (data:any) => {
		return new Promise((resolve, reject) => {
			api.user.login(data).then((res: Response) => {
				if (res && res.code === 200) {
					uni.setStorage({
						key: 'token',
						data: res.token,
						success: function() {
							getInfo().then(user => {
								resolve(user)
								uni.switchTab({
									url: '/pages/home/index'
								})
							})
						}
					})
				} else {
					reject(res)
				}
			})
		})
	}
	
	return { userId, userInfo, dept, login, getInfo }
});